(function() {
    // 用于存放小蛇的身体
    var snakeTags = [];

    function Snake(width, height, direction) {
        // 小蛇身体么一部分的宽高
        this.width = width || 20;
        this.height = height || 20;

        // 小蛇运动的方向
        this.direction = direction || 'right';

        //计算得分
        this.score = 0;

        // 小蛇的身体
        this.body = [{
            x: 3,
            y: 2,
            color: 'red'
        }, {
            x: 2,
            y: 2,
            color: 'orange'
        }, {
            x: 1,
            y: 2,
            color: 'orange'
        }];
    };


    // 对小蛇进行初始化
    Snake.prototype.init = function(map) {
        // console.log(snakeTags.length);

        remove();
        for (var i = 0; i < this.body.length; i++) {

            // 创建小蛇的的每一段身体
            var snakebody = document.createElement('div');

            // 把蛇的每一段身体放在地图中
            map.appendChild(snakebody);

            // 将小蛇在地图中渲染出来
            snakebody.style.position = 'absolute';
            snakebody.style.width = this.width + "px";
            snakebody.style.height = this.height + 'px';
            snakebody.style.left = this.body[i].x * this.width + 'px';
            snakebody.style.top = this.body[i].y * this.height + 'px';
            snakebody.style.backgroundColor = this.body[i].color;

            // 把蛇身存放到数组中，便于删除
            snakeTags.push(snakebody);
        }
        // console.log(snakeTags.length)
    };



    // 创建小蛇移动的函数
    Snake.prototype.move = function(food, map) {
        var i = this.body.length - 1;
        for (i; i > 0; i--) {
            this.body[i].x = this.body[i - 1].x;
            this.body[i].y = this.body[i - 1].y;
        }
        switch (this.direction) {
            case 'right':
                this.body[0].x += 1;
                break;
            case 'left':
                this.body[0].x -= 1;
                break;
            case 'top':
                this.body[0].y -= 1;
                break;
            case 'bottom':
                this.body[0].y += 1;
                break;
        }

        // 判断小蛇有没有吃到食物
        var headX = this.body[0].x * this.width + 'px';
        var headY = this.body[0].y * this.height + 'px';
        var foodX = food.x;
        var foodY = food.y;
        if (headX == foodX && headY == foodY) {
            var lastSnakeBody = this.body[this.body.length - 1];
            this.body.push({
                x: lastSnakeBody.x,
                y: lastSnakeBody.y,
                color: lastSnakeBody.color
            });
            this.score++;
            food.init(map);
        }

    }

    // 创建删除小蛇的函数
    function remove() {
        var i = snakeTags.length - 1;
        // console.log(snakeTags.length);
        for (i; i >= 0; i--) {
            var snakeTag = snakeTags[i];
            snakeTag.parentNode.removeChild(snakeTag);
            snakeTags.splice(i, 1);
        }
    }

    window.Snake = Snake;
})();